<?php


namespace App\Utility;


use App\Exceptions\ApiException;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Jwt\Exception;
use EasySwoole\Jwt\Jwt;

class JwtAuth
{

    public static function decodeToken($token)
    {
        $jwt_config = Config::getInstance()->getConf('JWT');
        $result = [];
        try {

            $jwtObject = Jwt::getInstance()->setSecretKey($jwt_config['SECRET'])->decode($token);
            $status = $jwtObject->getStatus();

            switch ($status) {
                case 1:
                    $result = [
                        'alg' => $jwtObject->getAlg(),
                        'aud' => $jwtObject->getAud(),
                        'data' => $jwtObject->getData(),
                        'exp' => $jwtObject->getExp(),
                        'iat' => $jwtObject->getIat(),
                        'iss' => $jwtObject->getIss(),
                        'nbf' => $jwtObject->getNbf(),
                        'jti' => $jwtObject->getJti(),
                        'sub' => $jwtObject->getSub(),
                        'signature' => $jwtObject->getSignature(),
                        'object' => $jwtObject
                    ];
                    break;
                case -1:
                    throw new ApiException('token已失效', 401);
                    break;
                case -2:
                    throw new ApiException("token已过期", 401);
                    break;
            }
        } catch (Exception $e) {
        }

        return $result;

    }

    public static function createToken($data = [])
    {
        $jwt_config = Config::getInstance()->getConf('JWT');
        $jwtObject = Jwt::getInstance()
            ->setSecretKey($jwt_config['SECRET'])// 秘钥
            ->publish();

        $expire_time = time() + 864000;
        $jwtObject->setAlg('HMACSHA256'); // 加密方式
        $jwtObject->setAud('user'); // 用户
        $jwtObject->setExp($expire_time); // 过期时间
        $jwtObject->setIat(time()); // 发布时间
        $jwtObject->setIss('QienPuppyPet'); // 发行人
        $jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
        $jwtObject->setNbf(time() + 60 * 5); // 在此之前不可用
        $jwtObject->setSub('Login_Token'); // 主题

// 自定义数据
        $jwtObject->setData($data);

        return $jwtObject->__toString();
    }


}